import { parse_node } from '../node_helper.js'
import { fields_helper } from '../node_helper.js'

export class O2mBase {
  constructor(payload = {}) {
    const { config, relation_node } = payload
    this._relation_node = relation_node
    this._config = config
  }

  get config() {
    return this._config
  }

  get relation_node() {
    return this._relation_node
  }

  get node() {
    return this.relation_node.node
  }

  check_has_sheet() {
    const { arch = {} } = this.config
    const { sheet = {} } = arch
    return Object.keys(sheet).length ? true : false
  }

  get fields() {
    const in_config = this.config.fields || {}
    const in_sheet = fields_helper.fields_get_in_views({
      view_type_name: this.config
    })

    const fs = fields_helper.merge_fields(in_config, in_sheet)

    if (Object.keys(fs).length) {
      return fs
    } else {
      return this.node.fields || {}
    }
  }

  get env() {
    return this.relation_node.env
  }

  get model() {
    return this.relation_node.model
  }

  get Model() {
    return this.relation_node.Model
  }

  get metadata() {
    return this.relation_node.metadata
  }

  get context() {
    return this.relation_node.context
  }

  get_parent_editmodel(parent_info) {
    const { model, metadata } = parent_info
    const Editmodel = this.env.editmodel(model, { metadata })

    return Editmodel
  }

  get_parent_data(parent_info = {}) {
    // call by get_arch_sheet
    const { record = {}, values = {} } = parent_info

    const Editmodel = this.get_parent_editmodel(parent_info)
    return Editmodel._merge_to_modifiers(record, values)
  }

  get_arch_for_node(node, kwargs = {}) {
    const get_fields = () => {
      const fields_in_config = this.relation_node.fields_in_config

      const models = this.relation_node.models_in_config
      const model_name = this.model

      function format_model_name(modelname) {
        return ['model', ...modelname.split('.')].join('_')
      }
      const fields_in_model =
        (models[format_model_name(model_name)] || {}).fields || {}

      return Object.keys(fields_in_config).reduce((acc, fld) => {
        acc[fld] = {
          ...(fields_in_model[fld] || {}),
          ...(fields_in_config[fld] || {})
        }
        return acc
      }, {})
    }

    const fields = get_fields()

    const metadata = this.metadata
    const context = this.context

    const user_groups = this.relation_node.rpc._groups.map(item => item.name)
    const kws1 = { fields, metadata, context, user_groups, env: this.env }
    const kws = { ...kws1, ...kwargs }
    const nodes = parse_node(node, kws)

    return nodes
  }
}
